# -*- coding: utf-8 -*-

"""
 (c) 2023 - Copyright CTyunOS Inc

 Authors:
   youyifeng <youyf2@chinatelecom.cn>

"""

import logging
from optparse import OptionParser

from cve_ease import activate_session
from cve_ease.models import CVE, SA, CVRF

logger = logging.getLogger('cve-ease')


def get_usage_str(usage):
    return usage + "\n(Specify the --help global option for a list of other help options)"


def handle_kernel(gconfig, db_session, args):
    """[basic] Kernel CVE tools"""
    usage = "usage: %prog kernel <options>"
    parser = OptionParser(usage=get_usage_str(usage))

    parser.add_option('-l', '--list', dest='list',
                      action='store_true', default=False,
                      help='list kernel info')
    parser.add_option('-i', '--info', dest='info', default="cve",
                      help='specific info type ["sa", "cve"]')
    parser.add_option('-d', '--dir', dest='dir', default="",
                      help='specific local kernel source dir')
    parser.add_option('-v', '--verbose', dest='verbose',
                      action='store_true', default=False,
                      help='show verbose output')

    (options, args) = parser.parse_args(args)

    session = activate_session(db_session, gconfig)
    logger.debug(" * active sql session")
    if options.list:
        def list_cve():
            cveDatabaseList = session.query(CVE).all()
            if 0 == len(cveDatabaseList):
                print(" WARNNING: no cve cache found! you should run 'cve-ease cve -m' to cache it.")
                return
            if options.verbose:
                CVE.pretty_output_title()
                for cve in cveDatabaseList:
                    if "kernel" in cve.packageName:
                        cve.simple_output()
            else:
                for cve in cveDatabaseList:
                    if "kernel" in cve.packageName:
                        cve.pretty_output()

        def list_sa():
            securityNoticeList = session.query(SA).all()
            if 0 == len(securityNoticeList):
                print(" WARNNING: no sa cache found! you should run 'cve-ease sa -m' to cache it.")
                return
            if options.verbose:
                SA.pretty_output_title()
                for sa in securityNoticeList:
                    if "kernel" in sa.affectedComponent:
                        sa.simple_output()
            else:
                for sa in securityNoticeList:
                    if "kernel" in sa.affectedComponent:
                        sa.pretty_output()

        def list_cvrf():
            cvrfNoticeList = session.query(CVRF).all()
            if 0 == len(cvrfNoticeList):
                print(" WARNNING: no sa cache found! you should run 'cve-ease cvrf -m' to cache it.")
                return
            for cvrf in cvrfNoticeList:
                if "kernel" in cvrf.packageName:
                    cvrf.format_output()

        if 'cve' == options.info:
            list_cve()
        elif 'sa' == options.info:
            list_sa()
        elif 'cvrf' == options.info:
            list_cvrf()
        else:
            print(f"unknown info type {options.info}")
    elif options.dir!="":
        print(f"set kernel dir {options.dir}")
    else:
        parser.print_help()
